<template>
  <div class="container">
    <div class="title-box">
      <img src="~@/assets/images/login_logo@2x.png" class="logo-img" alt />
      <p class="login-title">智慧教学平台</p>
      <img src="~@/assets/images/login_solgen@2x.png" class="logo-solgen" alt />
    </div>
    <div class="login-form">
      <p class="title">欢迎登录</p>
      <el-input v-model="loginNum" placeholder="请输入账号"></el-input>
      <el-input
        v-model="loginPassword"
        type="password"
        placeholder="请输入密码"
      ></el-input>
      <el-link @click="showPhone">忘记密码？</el-link>
      <el-button @click="submit">登录</el-button>
      <p style="text-align: center;font-size: 16px">
        还没有账号？
        <el-link
          style="color:#009CF6;margin-left: 0 "
          @click="userTypeMask = true"
          >立即注册</el-link
        >
      </p>
    </div>
    <div class="mask" v-if="isShow" @click="isShow = false">
      <div class="message"></div>
    </div>

    <!-- dialog 输入手机号-->
    <el-dialog
      :title="isRegister ? '注册账号' : '找回密码'"
      :center="true"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      width="500px"
      :visible.sync="phoneMask"
    >
      <el-form
        :model="infoForm"
        status-icon
        :rules="rules"
        ref="infoForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item prop="mobile">
          <el-input
            v-model="infoForm.mobile"
            autocomplete="off"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="plain" class="myBtn" @click="nextCode()"
          >下一步</el-button
        >
      </div>
    </el-dialog>

    <!-- dialog 输入验证码-->
    <el-dialog
      title="验证账号"
      :center="true"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      width="500px"
      :visible.sync="checkNumMask"
    >
      <!-- <el-row class="forbidden-row" >
        <el-col :span="6" class="forbidden">用户名</el-col>
        <el-col :span="14" class="forbidden">max</el-col>
      </el-row> -->
      <el-row class="forbidden-row">
        <el-col :span="24" class="forbidden"
          >验证码已经发送到手机{{ infoForm.mobile.slice(0, 4) }}****{{
            infoForm.mobile.slice(8)
          }}</el-col
        >
      </el-row>
      <el-row class="forbidden-row" type="flex" justify="space-between">
        <el-col :span="15">
          <el-input
            v-model="infoForm.validateCode"
            placeholder="请输入验证码"
          ></el-input>
        </el-col>
        <el-col :span="8">
          <el-button
            type="primary"
            :disabled="countdown > 0"
            @click="sendCode"
            >{{
            countdown &lt; 1 ? "重新发送" : countdown + "s"
            }}</el-button
          ></el-col
        >
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="plain" class="myBtn" @click="nextCheckNum"
          >下一步</el-button
        >
      </div>
    </el-dialog>

    <!-- 设置新的 密码 -->
    <el-dialog
      title="设置新密码"
      :center="true"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      width="500px"
      :visible.sync="newPWMask"
    >
      <div class="top-tip">请在5分钟之内修改密码！</div>
      <el-form
        label-position="top"
        :model="infoForm"
        status-icon
        :rules="rules"
        ref="ruleForm2"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="设置密码" prop="password">
          <el-input
            type="password"
            v-model="infoForm.password"
            autocomplete="off"
            placeholder="请输入不少于6位的密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPassword">
          <el-input
            type="password"
            v-model="infoForm.checkPassword"
            autocomplete="off"
            placeholder="两次密码需一致"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="plain" class="myBtn" @click="submitNewPw('ruleForm2')"
          >提交</el-button
        >
      </div>
    </el-dialog>

    <!-- 注册弹窗 -->
    <el-dialog
      title="注册账号"
      :center="true"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      width="550px"
      :visible.sync="userTypeMask"
    >
      <div
        :class="['role', { selectRole: userType === 2 }]"
        @click="userType = 2"
      >
        <div class="role-left">
          <span style="color:#101D37;font-size:20px;font-weight:900;"
            >我是学生</span
          >
          <span style="height:11px;"></span>
          <span style="color:#101D37;font-size:14px; opacity:0.3;"
            >student</span
          >
        </div>
        <div class="role-right">
          <img src="~@/assets/images/student.png" alt="" />
        </div>
      </div>
      <div
        :class="['role', { selectRole: userType === 1 }]"
        @click="userType = 1"
        style="margin: 48px 0;"
      >
        <div class="role-left">
          <span style="color:#101D37;font-size:20px;font-weight:900;"
            >我是老师</span
          >
          <span style="height:11px;"></span>
          <span style="color:#101D37;font-size:14px; opacity:0.3;"
            >teacher</span
          >
        </div>
        <div class="role-right">
          <img src="~@/assets/images/teacher.png" alt="" />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="plain" class="myBtn" @click="nextChoose"
          >下一步</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  userValidate,
  sendSms,
  validateSms,
  userAdd,
  userUpdatePwd,
  userLogin
} from '@/api/login'

import { setToken, setClassId, setResourceLessonId } from '@/utils/auth'

import { mapActions } from 'vuex'
// 检验手机号规则
let validatePhone = (rule, value, callbacka) => {
  let reg = /^1[3456789]\d{9}$/
  if (reg.test(value)) {
    callbacka()
  } else {
    callbacka('请填写正确的手机号')
  }
}

export default {
  name: 'login',
  data () {
    // 校验第二次密码
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.infoForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    // 校验第一次密码
    var validatePass = (rule, value, callback) => {
      if (value === '' || value.trim().length < 6) {
        callback(new Error('请至少输入6位密码'))
      } else {
        if (this.infoForm.checkPassword !== '') {
          this.$refs.ruleForm2.validateField('checkPass')
        }
        callback()
      }
    }
    return {
      phoneMask: false, // 忘记密码弹出层1
      checkNumMask: false, // 输入验证码弹出层2
      newPWMask: false, // 新密码确认弹出层3
      userTypeMask: false, // 注册角色选择弹窗
      userType: 1, // 1-老师，2-学生
      isRegister: true,
      countdown: 60,
      timer: null,
      loginNum: '',
      loginPassword: '',
      isShow: false,
      // 忘记密码手机号、验证码、新密码、验证新密码
      infoForm: {
        // 手机号,测试写死
        mobile: '',
        // 验证码
        validateCode: '',
        // 密码
        password: '',
        // 验证密码
        checkPassword: ''
      },
      // 忘记密码手机号校验规则
      rules: {
        mobile: [{ validator: validatePhone, trigger: 'blur' }],
        password: [{ validator: validatePass, trigger: 'blur' }],
        checkPassword: [{ validator: validatePass2, trigger: 'blur' }]
      }
    }
  },
  mounted () {},
  methods: {
    ...mapActions('user', ['setLoginInfo', 'setUserInfo', 'setClassList']),
    async submit () {
      if (!this.loginNum) {
        return this.$message.error('请输入账号')
      }
      if (!this.loginPassword) {
        return this.$message.error('请输入密码')
      }
      // 忘记密码
      const res = await userLogin({
        mobile: this.loginNum,
        password: this.loginPassword
      })
      if (res.code === '200') {
        setToken(res.data.token)
        setClassId(res.data.classId)
        setResourceLessonId(res.data.resourceLessonId)
        this.setUserInfo()
        this.setClassList()
        this.setLoginInfo(res.data)
        this.$message({
          message: '登陆成功',
          type: 'success',
          duration: 1000
        })
        this.$router.push({ name: 'index' })
      } else {
        this.$message.error(res.message)
      }
    },
    // 忘记密码按钮
    showPhone () {
      this.isRegister = false
      this.phoneMask = true
    },
    // 下一步
    nextCode () {
      this.$refs['infoForm'].validate(async valid => {
        if (valid) {
          // 手机号校验通过.调用发送短信接口
          // ---------- TODO---------------
          const res = await userValidate({ mobile: this.infoForm.mobile })
          if (res.code === '200') {
            if (this.isRegister) {
              if (res.data.exist === '0') {
                this.sendCode() // 账号不存在
              } else {
                this.$message.error('该手机号已注册')
              }
            } else {
              if (res.data.exist === '1') {
                this.sendCode() // 账号不存在
              } else {
                this.$message.error('该手机号未注册')
              }
            }
          } else {
            this.$message.error(res.message)
          }
        } else {

        }
      })
    },
    // 发送验证码
    async sendCode () {
      const res = await sendSms({ mobile: this.infoForm.mobile })
      if (res.code === '200') {
        // 开启验证码弹出层
        this.checkNumMask = true
        // 关闭手机号弹出层
        this.phoneMask = false
        this.timer = null
        this.countdown = 60
        clearInterval(this.timer)
        this.timer = setInterval(() => {
          this.countdown--
          if (this.countdown === 0) {
            clearInterval(this.timer)
          }
        }, 1000)
        this.$once('hook:beforeDestroy', () => {
          clearInterval(this.timer)
        })
      } else {
        this.$message.error(res.message)
      }
    },
    // 效验验证码
    async nextCheckNum () {
      if (!this.infoForm.validateCode) {
        return this.$message.error('请输入验证码')
      }
      const res = await validateSms({
        mobile: this.infoForm.mobile,
        validateCode: this.infoForm.validateCode
      })
      if (res.code === '200') {
        this.newPWMask = true
        this.checkNumMask = false
      } else {
        this.$message.error(res.message)
      }
    },
    // 确认新密码
    submitNewPw (formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          if (this.isRegister) {
            // 注册
            const res = await userAdd({
              mobile: this.infoForm.mobile,
              password: this.infoForm.password,
              userType: this.userType + ''
            })
            if (res.code === '200') {
              this.$message({
                message: '注册成功，请登录',
                type: 'success'
              })
            } else {
              this.$message.error(res.message)
            }
          } else {
            // 忘记密码
            const res = await userUpdatePwd({
              mobile: this.infoForm.mobile,
              password: this.infoForm.password
            })
            if (res.code === '200') {
              this.$message({
                message: '修改密码成功，请重新登录',
                type: 'success'
              })
            } else {
              this.$message.error(res.message)
            }
          }
          this.newPWMask = false
          // // 关闭手机号弹出层
        } else {

        }
      })
    },

    // 注册弹窗。选择身份
    nextChoose () {
      this.userTypeMask = false
      this.isRegister = true
      this.phoneMask = true
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  width: 100%;
  height: 100%;
  background: url("../../assets/images/banner.png") no-repeat;
  background-size: 100% 100%;
  .login-form {
    width: 500px;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0px 6px 11px 0px rgba(29, 70, 129, 0.24);
    border-radius: 5px;
    position: absolute;
    right: 20%;
    top: 20%;
    padding: 40px 0 50px 0;
    .title {
      font-size: 34px;
      font-weight: 500;
      color: rgba(0, 156, 246, 1);
      text-align: center;
      margin-bottom: 40px;
    }
    .el-input {
      display: block;
      width: 75%;
      height: 60px;
      margin: 0 auto;
      margin-top: 2%;
    }
    .el-link {
      margin-left: 75%;
      color: rgba(16, 29, 55, 1);
      opacity: 0.6;
      font-size: 16px;
    }
    .el-button {
      display: block;
      width: 61%;
      height: 11%;
      background: rgba(0, 156, 246, 1);
      border-radius: 10px;
      font-weight: 400;
      color: rgba(255, 255, 255, 1);
      font-size: 26px;
      margin: 20px auto;
    }
  }
  .title-box {
    position: absolute;
    left: 15%;
    top: 20%;
    display: flex;
    flex-flow: column nowrap;
    align-items: center;
    .logo-img {
      width: 184px;
      height: 127px;
    }
    .logo-solgen {
      width: 270px;
      height: 53px;
    }
    .login-title {
      font-size: 72px !important;
      color: #009cf6;
      font-weight: 600;
      margin-top: 33px;
      margin-bottom: 35px;
    }
  }
}
// 输入验证码样式
.forbidden-row {
  margin-bottom: 20px;
}
.forbidden {
  color: #989898;
  font-size: 20px;
}
// 两次密码样式
.top-tip {
  height: 15px;
  font-size: 16px;
  color: #009cf6;
  text-align: center;
  margin-top: -20px;
}

// 注册选择身份样式
.role {
  cursor: pointer;
  box-sizing: border-box;
  padding: 0 33px;
  width: 385px;
  height: 82px;
  border: 1px solid rgba(233, 233, 233, 1);
  border-radius: 20px;
  display: flex;
  justify-content: space-between;
  .role-left {
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
  .role-right {
    margin-top: -14px;
  }
}
.selectRole {
  background-color: #009cf6;
}
// 修改忘记密码输入框
::v-deep .el-dialog--center .el-dialog__body {
  padding: 25px 84px 5px;
}
::v-deep .el-dialog__title {
  width: 98px;
  height: 23px;
  font-size: 24px;
  font-weight: 500;
  color: rgba(16, 29, 55, 1);
}
::v-deep .el-form-item__content {
  margin-left: 0 !important;
}
//
.myBtn {
  font-size: 28px;
  font-weight: 500;
  line-height: 27px;
  color: rgba(0, 156, 246, 1);
  text-align: center;
  border: none;
}
// 按钮样式
::v-deep .el-dialog {
  border-radius: 10px;
  position: absolute;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
  margin-top: -80px !important;
}
</style>
